<template>
  <div>
    <a-modal :title="type == 'add' ? '新增规格' : '编辑规格'" :visible="visible" @before-open="open" @before-ok="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" width="1000px" :mask-closable="false">
      <div>
        <a-form auto-label-width ref="formRef" size="medium" :model="form">
          <a-space direction="vertical" :size="24">
            <a-row>
              <a-col :span="8">
                <a-form-item field="nameCn" label="规格中文名称" :rules="rules.nameCn">
                  <a-input placeholder="请输入规格中文名称" max-length="15" show-word-limit v-model="form.nameCn"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="nameEn" label="规格英文名称" :rules="rules.nameEn">
                  <a-input placeholder="请输入规格英文名称" v-model="form.nameEn"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="排序">
                  <a-input v-model="form.sort" placeholder="排序"></a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </a-space>
        </a-form>
      </div>
      <div class="title-bar">基础信息</div>
      <a-table class="table-two-line" size="mini" :pagination="false" :data="list" @change="handleChange" :draggable="{ type: 'handle', width: 40 }" :scroll="{ y: 380 }">
        <template #columns>
          <a-table-column title="序号" :width="40" #cell="{ rowIndex }">{{ rowIndex + 1 }} </a-table-column>
          <a-table-column>
            <template #title>
              <a-popover content="规格值标识用于生成SKU，只能使用4位以内的数字或英文字母，且在该规格内不能重复也不能修改">
                <p>
                  <span class="required">规格值标识</span>
                  <icon-question-circle />
                </p>
              </a-popover>
            </template>
            <template #cell="{ record }">
              <a-input :disabled="type != 'add' && !record.isEditAdd" placeholder="请输入1-4位数字或英文字母" @input="setValueCap($event, record)" max-length="4" show-word-limit v-model:model-value="record.valueCode" allow-clear />
            </template>
          </a-table-column>
          <a-table-column>
            <template #title>
              <span class="required">规格值中文</span>
            </template>
            <template #cell="{ record }">
              <a-input placeholder="请输入" max-length="15" show-word-limit v-model:model-value="record.valueCn" allow-clear />
            </template>
          </a-table-column>
          <a-table-column>
            <template #title>
              <span class="required">规格值英文</span>
            </template>
            <template #cell="{ record }">
              <a-input placeholder="请输入" v-model:model-value="record.valueEn" allow-clear />
            </template>
          </a-table-column>
          <a-table-column title="操作" #cell="{ record, rowIndex }" :width="120">
            <a-button class="gray-outline" size="mini" @click="addItem">
              <icon-plus />
            </a-button>
            <a-button class="gray-outline ml10" :disabled="!list[1]" size="mini" @click="list.splice(rowIndex, 1)">
              <icon-minus />
            </a-button>
          </a-table-column>
        </template>
      </a-table>

      <template #footer>
        <a-button class="gray-outline" @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="loading" @click="handleOk">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed } from 'vue'
  import { findWarehouseListByParam } from '@/api/warehouse'
  import { saveOrUpdateProductSpec, getProductSpecById } from '@/api/product'
  import { updatePackageWarehouse } from '@/api/order'
  import { Message } from '@arco-design/web-vue'
  import _ from 'lodash-es'
  export default defineComponent({
    props: ['type', 'info'],
    setup(props: any, { emit }) {
      let visible = ref(false)
      const formRef = ref()
      const data: any = reactive({
        form: {},
        rules: {
          nameCn: [{ required: true, message: '请输入规格中文名称' }],
          nameEn: [{ required: true, message: '请输入规格英文名称' }],
        },
        loading: false,
        list: [],
      })

      const open = () => {
        data.list = []
        if (props.type == 'add') addItem()
        if (props.type == 'edit') {
          getDetail()
        }
      }

      const getDetail = async () => {
        const res: any = await getProductSpecById({ id: props.info.id })
        data.form = res.data
        data.list = data.form.valueList
      }

      const addItem = () => {
        let obj: any = {
          valueCn: '',
          valueEn: '',
        }
        if (props.type == 'edit') {
          obj.isEditAdd = true
        }
        data.list.push(obj)
      }

      const handleOk = () => {
        formRef.value.validate(async (valid: any) => {
          if (!valid) {
            for (let index = 0; index < data.list.length; index++) {
              const element = data.list[index]
              if (!element.valueCode) {
                return Message.error(`序号为${index + 1}的规格值标识必填`)
              }
              if (!element.valueCn) {
                return Message.error(`序号为${index + 1}的规格值中文必填`)
              }
              if (!element.valueEn) {
                return Message.error(`序号为${index + 1}的规格值英文文必填`)
              }
            }

            let params = {
              ...data.form,
              valueList: data.list,
            }
            data.loading = true
            try {
              const res: any = await saveOrUpdateProductSpec([params])
              if (res.code == 'SUCCESS') {
                props.type == 'add' ? Message.success('新增成功') : Message.success('编辑成功')
                handleCancel()
                emit('save')
              }
            } catch (error) {}
            data.loading = false
          }
        })
      }

      const handleCancel = () => {
        data.list = []
        data.form = {}
        formRef.value.resetFields()
        formRef.value.clearValidate()
        visible.value = false
      }

      const handleChange = (list: any) => {
        data.list = list
      }

      const setValueCap = _.debounce((val: string, item: any) => {
        let newStr = val.toLocaleUpperCase()

        // let index = data.list.findIndex((e: any) => e.valueCode == newStr)
        // console.log(index)
        // if (index != -1) {
        //   item.valueCode = ''
        //   return Message.error('同一规格里面规格标识不能重复')
        // }
        item.valueCode = newStr
      }, 500)

      return {
        ...(toRefs(data) as any),
        visible,
        formRef,
        open,
        handleOk,
        handleCancel,
        handleChange,
        addItem,
        setValueCap,
      }
    },
  })
</script>

<style lang="less" scoped></style>
